package org.h.apiinterface.aop;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.h.apiinterface.util.JacksonUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Slf4j
@Component
public class AopTest {
    @Pointcut("execution(* org.h.apiinterface.controller.*.*(..))")
    public void test() {

    }





    //切点之前
    @Before("test()")
    public void beforeAdvice(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        log.info("--------------------begin-----------------"+ request.getRequestURL().toString());
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());

        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        // 打印请求的 IP
        log.info("IP1             : {}", request.getRemoteAddr());
        log.info("IP2             : {}",  request.getHeader("X-Forwarded-For"));
        // 打印请求入参
        log.info("Request Args   : {}", getParams(joinPoint));


    }

    //环绕
    @Around("test()")
    public Object  aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) {
        long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            result = proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        // 打印出参
        try {
            log.info("返回结果  : {}", JacksonUtils.objectToJson(result));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        // 执行耗时
        // log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // HttpServletRequest request = attributes.getRequest();
        // log.info("--------------------end-----------------"+ request.getRequestURL().toString());
        return result;
    }




    private String getParams(JoinPoint joinPoint) {
        String params = "";
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                Object arg = joinPoint.getArgs()[i];
                if ((arg instanceof HttpServletResponse) || (arg instanceof HttpServletRequest)
                        || (arg instanceof MultipartFile) || (arg instanceof MultipartFile[])) {
                    continue;
                }
                try {
                    params +=JacksonUtils.objectToJson(joinPoint.getArgs()[i]);
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            }
        }
        return params;
    }


}
